package flca.projbuilder.gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import flca.projbuilder.dto.TemplateDto;

public class AskValuesGui extends JFrame {

	private static final long serialVersionUID = -8421553899279889567L;

	private static final String TARGET_DIR = "_target_dir_";
	
	private JPanel centre;
	private JButton finishBtn;
	
	private Set<TemplateDto> templates;
	private ICloseGui callback;
	private TemplateDto currTemplate;
	private JTextField targetDir;
	
	public AskValuesGui(Set<TemplateDto> templates, ICloseGui aCallback) {
		this.templates = templates;
		this.callback = aCallback;
		initUI();
	}

	public final void initUI() {

		add(makeTopPanel(), BorderLayout.NORTH);
		centre = makeCentre();
		add(centre, BorderLayout.CENTER);
		add(makeBottomPanel(), BorderLayout.SOUTH);

		setSize(350, 300);
		setTitle("Project builder");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
	}

	private JPanel makeTopPanel() {
		JPanel top = new JPanel();

		JLabel label = new JLabel("Template");
		top.add(label);

		JComboBox<String> cb = new JComboBox<String>(getTemplateNames());
		top.add(cb);
		cb.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent ie) {
				String selcname = ie.getItem().toString();
				if (selcname != null && selcname.trim().length() > 0) {
					setSelectedTemplate(selcname);
					updateCentre();
				}
			}
		});
		
		return top;
	}
	
	private String[] getTemplateNames() {
		List<String> r = new ArrayList<>();
		r.add("");
		for (TemplateDto td : templates) {
			r.add(td.getName());
		}
		return r.toArray(new String[r.size()]);
	}

	private JPanel makeCentre() {
		JPanel p = new JPanel();
		
		JLabel lbl = new JLabel("select template that you want to process..");
		p.add(lbl);

		return p;
	}

	private JPanel makeBottomPanel() {
		JPanel p = new JPanel();

		finishBtn = new JButton("finish");
		finishBtn.setEnabled(false);
		finishBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	callback.onFinish(updateCurrentTemplate());
            }
        });   
		p.add(finishBtn);

		return p;
	}
	
	private TemplateDto updateCurrentTemplate() {
		TemplateDto r = currTemplate;
		
		for (Component comp : centre.getComponents()) {
			if (comp instanceof JTextField) {
				JTextField tf = (JTextField) comp;
				if (TARGET_DIR.equals(tf.getName())) {
					r.setToDir(tf.getText());
				} else {
					r.updateValue(tf.getName(), tf.getText());
				}
			}
		}
		
		return r;
	}
	
	private void setSelectedTemplate(String aName) {
		for (TemplateDto td : templates) {
			if (td.getName().equals(aName)) {
				currTemplate = td;
				break;
			}
		}
	}
	
	private void updateCentre() {
		centre.removeAll();
		centre.setLayout(new GridBagLayout());
		addDescription();
		addTargetDir();
		addFromToFields();
		pack();
	}

	private void addDescription() {
		JLabel l = new JLabel(currTemplate.getDescription());
		centre.add(l, makeConstraint(0, 0));
	}

	private void addTargetDir() {
		JLabel l = new JLabel("target-dir");
		targetDir = new JTextField();
		JButton btn = new JButton("..");
		btn.setPreferredSize(new Dimension(20, 20));
		targetDir.setName(TARGET_DIR);
		btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	getTargetDir();
            }
        });    
		
		centre.add(l, makeConstraint(1, 0));
		centre.add(targetDir, makeConstraint(1, 1));
		centre.add(btn, makeConstraint(1, 2));
	}

	private void addFromToFields() {
		int row = 2;
		for (String key : currTemplate.getFromTos().keySet()) {
			JLabel l = new JLabel(key + " : " );
			JTextField fld = makeToField(key);
			JButton helpbtn = makeHelpButton(key);
			centre.add(l, makeConstraint(row, 0));
			centre.add(fld, makeConstraint(row, 1));
			centre.add(helpbtn, makeConstraint(row, 2));
			row++;
		}
	}

	private JButton makeHelpButton(String key) {
		ImageIcon theIcon = new ImageIcon("help.gif");
		JButton helpbtn = new JButton(theIcon);
		helpbtn.setBorder(BorderFactory.createEmptyBorder());
		helpbtn.setToolTipText(currTemplate.getFromTos().get(key));
		return helpbtn;
	}

	private JTextField makeToField(String key) {
		JTextField fld = new JTextField();
		fld.setName(key);
		fld.setColumns(20);
		fld.setToolTipText(currTemplate.getFromTos().get(key));
		fld.addKeyListener(new KeyAdapter() {
		    public void keyReleased(KeyEvent e) {
		    	updateGui();
		    }
		});
		return fld;
	}

	private void getTargetDir() {
		JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int returnVal = fc.showOpenDialog(this);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			targetDir.setText(fc.getSelectedFile().getPath());
			updateGui();
		}
	}
	

	private GridBagConstraints makeConstraint(int row, int col) {
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridy = row;
		c.gridx = col;
		return c;
	}
	
	private void updateGui() {
		boolean r = true;
		
		for (Component comp : centre.getComponents()) {
			if (comp instanceof JTextField) {
				JTextField tf = (JTextField) comp;
				if (tf.getText() == null || tf.getText().trim().length() == 0) {
					r = false;
				}
			}
		}
		
		finishBtn.setEnabled(r);
	}
}